<?php

class Staff_controller extends Application_controller {

// 	public $before_filter = array('get_nav_bar');

	function index() {
		//$this->login();
		$this->render( $_GET['controller'], 'menu' );
	}

	function viewProfile() {
		//$this->only_customer_users = User::find('all', 'User', array('joins' => array("customers" => "users.id = customers.user_id")));
		$this->customers = Customer::find('all');
		$this->customer = false;
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			if (isset($_POST['customer_profile_search']) && ($_POST['customer_profile_search'] == 'customer_name_cb') && ($_POST['cust_name_cid'] != '-1')) { $cust_id = intval($_POST['cust_name_cid']); }
			elseif (isset($_POST['customer_profile_search']) && ($_POST['customer_profile_search'] == 'company_cb') && ($_POST['company_cid'] != '-1')) { $cust_id = intval($_POST['company_cid']); }
			if (isset($cust_id)) { $this->customer = Customer::find($cust_id); }
		}
	}

	function menu() {
		
	}

	function customer() {
		$customers = Customer::find('all');
		$users = array();
		foreach($customers as $customer) { array_push($users, $customer->user);	}
		$this->users = $users;
		switch ($this->crud_manager()) {
			case 'new':
				$this->user = new User();
			break;
			case 'create':
				$user = new User($_POST['user']);
				if ($user->save()) {
					$customer = new Customer();
					$customer->hashed_password = $_POST['cust_hashed_pass'];
					$customer->user = $user;
					if ($customer->save()) { return $this->redirect('staff', __FUNCTION__); }
					$this->setnotice('customer failed to save: user saved successfully');
					$this->render('staff', __FUNCTION__);
				}
				$this->setnotice('user failed to save!');
				$this->render('staff', __FUNCTION__);
			break;
			case 'edit':
				$this->user = User::find($_GET['id']);
			break;
			case 'update':
				$user = User::find($_GET['id']);
				if ($user->update($_POST['user'])) {
					$this->setnotice('Customer updated successfully!');
					return $this->redirect('staff', __FUNCTION__);
				}
				$this->setnotice('Customer NOT updated!');
				$this->render('staff', __FUNCTION__);
			break;
			case 'destroy':
				$user = User::find($_GET['id']);
				$user->customer->destroy();
				$this->setnotice('Customer has been successfully removed!');
				$this->redirect('staff', __FUNCTION__);
			break;
			default;
				echo 'crud manager couldnt select';
			break;
		}
	}



	function product() {
		//this is where you get to crud product.
		$this->products = Product::find('all'); //WAITING FOR 5.3 TO BUSS $products = Product::find('all')
		$this->all_playground_equipments = Playgroundequipment::find('all');
		//echo $_GET['apple'];
		switch ($this->crud_manager()) {
			case 'new':
// 				echo 'new';
				$this->product = new Product();
			break;
			case 'create':
// 				echo 'create';
				//print_r($_POST['equipments']);
				$product = new Product($_POST['product']);
				if ($product->save()) {
					foreach ($this->get_playgroundequipments_from_ids($_POST['equipments']) as $play_eq) {
						$product->append_many_to_many($play_eq);
					}
					if (isset($_FILES['images'])) {
						foreach($this->process_uploaded_images_for_model($_FILES['images']) as $image_attrs) {
							$image = new Productimage($image_attrs);
							$product->append_to_many($image);
						}
					}
					
					$this->setnotice('Product saved successfully!');
					$this->redirect('staff', 'product');
				}
				else {
					$this->setnotice('Product NOT SAVED!');
					$this->render('staff', 'product');
				}
				
			break;
			case 'edit':
// 				echo 'edit';
				$this->product = Product::find($_GET['id']);
			break;

//   def update
// 	@all_equipments = get_all_equipments
// 	checked_equipments = get_equipments_from(params[:equipments])
// 	removed_equipments = @all_equipments - checked_equipments
//     @product = Product.find(params[:id])
// 	@product.updated_by = session[:employee_id]
//     if @product.update_attributes(params[:product])
// 	checked_equipments.each {|equip| @product.playgroundequipments << equip if !@product.playgroundequipments.include?(equip) }
// 	removed_equipments.each {|equip| @product.playgroundequipments.delete(equip) if @product.playgroundequipments.include?(equip) }
//       flash[:notice] = 'Product was successfully updated.'
//       redirect_to :action => 'show', :id => @product
//     else
//       render :action => 'edit'
//     end

			case 'update':
// 				echo 'update';
				$all_playground_equipments = Playgroundequipment::find('all');
				
				$checked_playgroundequipments = isset($_POST['equipments']) ? $this->get_playgroundequipments_from_ids($_POST['equipments']) : array();

				$removed_playgroundequipments = array_diff($all_playground_equipments, $checked_playgroundequipments);


				$product = Product::find($_GET['id']);

				if ($product->update($_POST['product'])) {
					foreach ($checked_playgroundequipments as $chk_pl_eq_ob) {
						if (!in_array($chk_pl_eq_ob, $product->playgroundequipments)) {
							$product->append_many_to_many($chk_pl_eq_ob);
						}
					}
					foreach ($removed_playgroundequipments as $rmvd_pl_eq_ob) {
						if (in_array($rmvd_pl_eq_ob, $product->playgroundequipments)) {
							$product->remove_many_to_many($rmvd_pl_eq_ob);
						}
					}
					$this->setnotice('Product updated successfully!');
					$this->redirect('staff', 'product');
				}
				else {
					$this->product = $product;
					$this->setnotice('Product NOT updated!');
					$this->render('staff', 'product');
				}
			break;
			case 'destroy':
// 				echo 'destroy';
				$product = Product::find($_GET['id']);
				$product->destroy();
				$this->setnotice('Product has been successfully removed!');
				$this->redirect('staff', 'product');
			break;
			default;
				echo 'crud manager couldnt select';
			break;
		}
	}


	function get_playgroundequipments_from_ids($playgroundequipment_id_array) {
		$playgroundequipments_object_array = array();
		foreach ($playgroundequipment_id_array as $eq_id) {
			array_push($playgroundequipments_object_array, Playgroundequipment::find(intval($eq_id)));
		}
		return $playgroundequipments_object_array;
	}
	

	function playgroundEquipment() {
		//this is where you get to crud playgroundequipment.
		$this->playgroundequipments = Playgroundequipment::find('all');
		switch ($this->crud_manager()) {
			case 'new':
				$this->playgroundequipment = new Playgroundequipment();
			break;
			case 'create':
				$playgroundequipment = new Playgroundequipment($_POST['playgroundequipment']);
				if ($playgroundequipment->save()) {
					$this->setnotice('Playgroundequipment saved successfully!');
					$this->redirect('staff', __FUNCTION__);
				}
				else {
					//print_r($playgroundequipment);
					$this->setnotice('Playgroundequipment NOT SAVED!');
					$this->render('staff', __FUNCTION__);
				}
			break;
			case 'edit':
				$this->playgroundequipment = Playgroundequipment::find($_GET['id']);
			break;
			case 'update':
				//print_r($_POST['playgroundequipment']);
				$playgroundequipment = Playgroundequipment::find($_GET['id']);
				if ($playgroundequipment->update($_POST['playgroundequipment'])) {
					$this->setnotice('Playgroundequipment updated successfully!');
					$this->redirect('staff', __FUNCTION__);
				}
				else {
					$this->setnotice('Playgroundequipment NOT updated!');
					$this->render('staff', __FUNCTION__);
				}
			break;
			case 'destroy':
				$playgroundequipment = Playgroundequipment::find($_GET['id']);
				$playgroundequipment->destroy();
				$this->setnotice('Playgroundequipment has been successfully removed!');
				$this->redirect('staff', __FUNCTION__);
			break;
			default;
				echo 'crud manager couldnt select';
			break;
		}
	}

/*
class ProductsController < ApplicationController

	before_filter :autherize_general_staff_access

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @product_pages, @products = paginate :products, :per_page => 10
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
	@all_equipments = get_all_equipments
  end

  def create
	@all_equipments = get_all_equipments
	checked_equipments = get_equipments_from(params[:equipments])
	removed_equipments = @all_equipments - checked_equipments
    @product = Product.new(params[:product])
	@product.created_by = session[:employee_id]
	@product.updated_by = session[:employee_id]
    if @product.save
	checked_equipments.each {|equip| @product.playgroundequipments << equip if !@product.playgroundequipments.include?(equip) }
	removed_equipments.each {|equip| @product.playgroundequipments.delete(equip) if @product.playgroundequipments.include?(equip) }
      flash[:notice] = 'Product was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
	@all_equipments = get_all_equipments
    @product = Product.find(params[:id])
  end

  def update
	@all_equipments = get_all_equipments
	checked_equipments = get_equipments_from(params[:equipments])
	removed_equipments = @all_equipments - checked_equipments
    @product = Product.find(params[:id])
	@product.updated_by = session[:employee_id]
    if @product.update_attributes(params[:product])
	checked_equipments.each {|equip| @product.playgroundequipments << equip if !@product.playgroundequipments.include?(equip) }
	removed_equipments.each {|equip| @product.playgroundequipments.delete(equip) if @product.playgroundequipments.include?(equip) }
      flash[:notice] = 'Product was successfully updated.'
      redirect_to :action => 'show', :id => @product
    else
      render :action => 'edit'
    end
  end

  def destroy
    Product.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

	private #-------------

	def get_all_equipments
		return Playgroundequipment.find(:all)
	end

	def get_equipments_from(equip_list)
		equip_list = [] if equip_list.blank?
		return equip_list.collect {|peid| Playgroundequipment.find_by_id(peid)}.compact
	end


end

*/


/*
<%= error_messages_for 'product' %>

<!--[form:product]-->
<p><label for="product_summary">Summary</label><br/>
<%= text_field 'product', 'summary'  %></p>

<p><label for="product_description">Description</label><br/>
<%= text_field 'product', 'description'  %></p>

<p><label for="product_material">Material</label><br/>
<%= text_field 'product', 'material'  %></p>

<p><label for="product_price">Price</label><br/>
<%= text_field 'product', 'price'  %></p>

<p><label for="product_mountingprice">Mounting Price</label><br/>
<%= text_field 'product', 'mounting_price'  %></p>

<p><label for="product_warentee">Warentee years</label><br/>
<%= text_field 'product', 'warentee'  %></p>

<p><label for="product_dimensions">Dimensions in feet</label><br/>
<table>

<tr>
<td><th>Length</th></td>
<td><%= text_field 'product', 'length_dimension' %></td>
</tr>
<tr>
<td><th>Width</th></td>
<td><%= text_field 'product', 'width_dimension' %></td>
</tr>
<tr>
<td><th>Height</th></td>
<td><%= text_field 'product', 'height_dimension'  %></td>
</tr>
</tbody>
</table>
<!--[eoform:product]-->
<p><label for="product_type">Product type</label><br/>
<% @all_equipments.each do |equip| -%>
<%= check_box_tag('equipments[]', equip.id, @product.playgroundequipments.map {|pe| pe.id }.include?(equip.id)) -%> <%= equip.name -%><br />
<% end -%>
<br />

*/

/*
	def manage
		@topic_pages, @topics = paginate :topics, :per_page => 10
		if request.get? #---------------new edit
			if !params[:id] #----------new
				@topic = Topic.new
			else		#----------edit
				@topic = Topic.find(params[:id])
			end
		elsif request.post?
			if !params[:id] #---------create
				@topic = Topic.new(params[:topic])
				@topic.created_by = session[:employee_id]
				@topic.updated_by = session[:employee_id]
				if @topic.save
					flash[:notice] = 'Topic was successfully created.'
					redirect_to :action => 'manage'
				else
					render :action => 'manage'
				end
			else		#-----------update dleete
				if params[:commit] == 'Edit'	#-----------update
					@topic = Topic.find(params[:id])
					@topic.updated_by = session[:employee_id]
					if @topic.update_attributes(params[:topic])
						flash[:notice] = 'Topic was successfully updated.'
						redirect_to :action => 'manage', :id => @topic
					else
						render :action => 'manage'
					end
				else				#--------------deleet
					Topic.find(params[:id]).destroy
					flash[:notice] = 'Topic was successfully Deleted.'
					redirect_to :action => 'manage', :id => nil, :page => params[:page]
				end
			end
		end
	end


*/


	//login works username 1 pass 1
	function process_login() {
		$found_user = Employee::authenticate($_POST['username'],$_POST['password']);
		if ($found_user) {
			$_SESSION['login_indicator_uname'] = $found_user->user()->first_name;
			$this->setnotice('Welcome back, you are now logged in ' . $_POST['username']);
			return $this->redirect('staff', 'menu.html');
		}
		$this->setnotice('You have entered an invalid username or password.');
		return $this->redirect('staff', 'login.html');
	}


	function newCustomer() {

		//it just occured to me i dont need to do the following lines...:S
		//yes i dont...but its good practice that i do, say if i needed some object attributes...:s
		//also i have made it a lil less error prof by adding issets in text_field()
		//$val = isset($this_copy->$obj_name->$param) ? $this_copy->$obj_name->$param : "";
		//if no isset. i would HAVE TO initalise an object!
		
		$this->customer = new Customer();

	}

	function saveCustomer() {
		$cust_hashed_password = $_POST['customer']['hashed_password'];
		unset($_POST['customer']['hashed_password']);
		$user = new User($_POST['customer']);
		if ($user->save()) {
			$customer = new Customer();
			$customer->hashed_password = $cust_hashed_password;
			$customer->user = $user;
			if ($customer->save()) { return $this->redirect('public', 'savePerformaInvoice'); }
			echo 'customer failed to save: user saved successfully';
		}
		echo 'user failed to save';
	}



}

?>